'use strict';

const BaseService = require('./base');
const modelName = 'IdleCity';
class RouterService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }
  async getTree(query = {}) {
    const { ctx } = this;
    const { type } = query;
    const where = {};
    if (type) {
      where.type = type;
    }

    // 获取所有分类
    const categories = await ctx.model.IdleCategory.findAll({
      where,
      order: [['sort', 'ASC'], ['id', 'DESC']]
    });

    // 构建树形结构
    const categoryMap = {};
    const result = [];

    categories.forEach(category => {
      categoryMap[category.id] = {
        id: category.id,
        name: category.name,
        parent_id: category.parent_id,
        type: category.type,
        sub_type: category.sub_type,
        sort: category.sort,
        children: []
      };
    });

    categories.forEach(category => {
      if (category.parent_id === 0) {
        result.push(categoryMap[category.id]);
      } else {
        if (categoryMap[category.parent_id]) {
          categoryMap[category.parent_id].children.push(categoryMap[category.id]);
        }
      }
    });

    return result;
  }

}


module.exports = RouterService;
